<?php

namespace App\Services\Oauth;

use App\Exceptions\Response\Service\ServiceCode;
use App\Exceptions\Response\Service\ServiceException;
use App\Models\Oauth\UserModel;
use App\Core\Utils\TwHelper\CommFunction;
use App\Models\Oauth\UserTypeModel;
use App\Models\Oauth\UserTypeMapModel;
use App\Models\Oauth\UserProfileModel;
use App\Models\Base\DistrictModel;
use App\Services\Utils\TencentYun\ImageService;
use App\Models\Club\MemberModel;
use App\Models\Oauth\UserLoginLogModel;
use App\Models\Oauth\DistrictModel as OauthDistrictModel;
use App\Models\Oauth\UserLoginOauthModel;
use App\Models\Oauth\CountryCodeModel;

class UserService
{

    /**
     *修改密码
     */
    public function changePassword($id, $password)
    {
        $randomKey = CommFunction::makeRandomKey();
        $makePassword = CommFunction::makePassword(trim($password), $randomKey);
        $data['password'] = $makePassword;
        $data['key'] = $randomKey;
        $data['updated'] = time();
        if (!UserModel::updateUser($id, $data)) {
            throw new ServiceException(ServiceCode::SERVICE_OAUTH_CHANGE_PASSWORD_FAIL, '', []);
        }
        return true;
    }

    /**
     * 验证手机号码
     */
    public function checkMobile($mobile)
    {
        $where['mobile'] = $mobile;
        $user = UserModel::getUserData($where);
        if ($user) {
            return $user['id'];
        }
        return false;
    }

    /**
     * 获取用户类型列表
     */
    public function getUserTypes()
    {
        return UserTypeModel::getUserType();
    }

    /**
     * 设置用户类型
     */
    public function setUserType($id, $userTypes)
    {
        if (!$id || !$userTypes) {
            throw new ServiceException(ServiceCode::SERVICE_PARAM_INVALID, '', []);
        }

        $oldUserTypes = UserTypeMapModel::getUserType(array('user_id' => $id));
        $oldUserTypeIds = array();
        if ($oldUserTypes) {
            for ($i = 0; $i < count($oldUserTypes); $i++) {
                $oldUserTypeId = $oldUserTypes[$i]['type_id'];
                $oldUserTypeIds[$i] = $oldUserTypeId;
                //删除不存在的类型
                if (!in_array($oldUserTypeId, $userTypes)) {
                    $where['id'] = $oldUserTypes[$i]['id'];
                    UserTypeMapModel::delUserType($where);
                }
            }
        }

        //添加新增的用户类型
        foreach ($userTypes as $newTypeId) {
            if ($oldUserTypeIds) {
                //是新增的
                if (!in_array($newTypeId, $oldUserTypeIds)) {
                    UserTypeMapModel::addUserType($id, $newTypeId);
                }
            } else {
                UserTypeMapModel::addUserType($id, $newTypeId);
            }
        }
        return true;
    }

    /**
     * 获取用户信息
     */
    public function getUserInfo($uid)
    {
        $data = array();
        $result = UserModel::getUserById($uid);
        $data['id'] = $result['id'];
        $data['name'] = $result['name'];
        $data['nickname'] = $result['nickname'];
        $data['username'] = $result['username'];
        $data['mobile'] = $result['mobile'];
        //性别0未设置 1女 2男
        if ($result['sex'] == 1) {
            $data['sex'] = '女';
            $data['sexid'] = 1;
        } elseif ($result['sex'] == 2) {
            $data['sex'] = '男';
            $data['sexid'] = 2;
        } else {
            $data['sex'] = '未设置';
            $data['sexid'] = 0;
        }
        $data['avatar'] = $result['avatar'];
        //查询用户的类型
        $usertypes = UserTypeMapModel::getUserTypeName($uid);
        $data['type'] = $usertypes;
        //查询用户的地址信息
        $userProfile = UserProfileModel::getUserProfile(array('user_id' => $uid));
        $address = '';
        if ($userProfile) {
            //省
            $provinceId = $userProfile['province'];
            if ($provinceId) {
                $province = DistrictModel::findById($provinceId, array('name'));
                $provinceName = $province[0]['name'];
                $userAddress['provinceId'] = $provinceId;
                $userAddress['provinceName'] = $provinceName;
                $address .= $provinceName;
                //市
                $cityId = $userProfile['city'];
                if ($cityId) {
                    $city = DistrictModel::findById($cityId, array('name'));
                    $cityName = $city[0]['name'];
                    $userAddress['cityId'] = $cityId;
                    $userAddress['cityName'] = $cityName;
                    $address .= $cityName;
                    //区县
                    $areaId = $userProfile['area'];
                    if ($areaId) {
                        $area = DistrictModel::findById($areaId, array('name'));
                        $areaName = $area[0]['name'];
                        $userAddress['areaId'] = $areaId;
                        $userAddress['areaName'] = $areaName;
                        $address .= $areaName;
                        //乡镇
                        $townId = $userProfile['town'];
                        if ($townId) {
                            $town = DistrictModel::findById($townId, array('name'));
                            $townName = $town[0]['name'];
                            $userAddress['townId'] = $townId;
                            $userAddress['townName'] = $townName;
                            $address .= $townName;
                        }
                    }
                }
            }
            $data['detailAddress'] = $userProfile['address'];
            $address .= $userProfile['address'];
            $data['userAdress'] = $userAddress;
        }
        $data['address'] = $address;
        //头像
        $data['avatarId'] = $data['avatar'];
        $data['avatar'] = ImageService::makeDownloadUri($data['avatar']);
        return $data;
    }

    /**
     * 设置用户信息
     */
    public function setUserInfo($id, $data)
    {
        if (!UserModel::updateUser($id, $data)) {
            throw new ServiceException(ServiceCode::SERVICE_OAUTH_SET_AVATAR_FAIL, '', []);
        }
        return true;
    }

    /**
     * 设置bbs用户信息
     */
    public function setBbsUserInfo($id, $data)
    {
        if (MemberModel::updateBbsUser($id, $data)) {
            return true;
        }
        return false;
    }

    /**
     * 用户登录时判断是否设置了地理信息，如果没有自动设置一个
     */
    public function addUserProfile($uid)
    {
        $where['user_id'] = $uid;
        $userProfile = UserProfileModel::getUserProfile($where);
        if (!$userProfile) {
            $registService = new RegistService();
            $registService->addUserProfile($uid);
        }
    }

    /**
     * 获取地理信息
     */
    public function getDistrict($upid)
    {
        if ($upid) {
            return DistrictModel::selectByUpid($upid);
        } else {
            $where['level'] = 1;
            return OauthDistrictModel::getDistricts($where);
        }
    }

    /**
     * 更新用户的地理信息
     */
    public function updateUserProfile($uid, $data)
    {
        return UserProfileModel::updateUserProfile($uid, $data);
    }

    /**
     * 获取绑定相关信息(手机号、微信、QQ)
     */
    public function getBoundInfo($uid)
    {
        $result = UserModel::getUserById($uid);
        $data = array();
        if ($result && $result['mobile']) {
            $data['mobile'] = $result['mobile'];
        }
        $where['user_id'] = $uid;
        $where['status'] = UserLoginOauthModel::STATUS_NOMAL;
        $loginOauths = UserLoginOauthModel::getLoginOauths($where);
        if ($loginOauths) {
            foreach ($loginOauths as $loginOauth) {
                if ($loginOauth['type'] == 1) {
                    $data['weixin'] = $loginOauth['open_id'];
                }
                if ($loginOauth['type'] == 2) {
                    $data['qq'] = $loginOauth['open_id'];
                }
            }
        }
        return $data;
    }


    /**
     * 获取国际电话区号
     */
    public function getCountryCode()
    {
        return CountryCodeModel::getCountryCode();
    }

}